package gt.controller.settle;

import gt.common.UrlConstant;
import gt.controller.base.BaseController;
import gt.entity.bound.Bound;
import gt.entity.token.Token;
import gt.service.bound.BoundService;
import gt.service.token.TokenService;
import gt.util.CookieUtil;
import gt.util.HttpHelper;
import gt.util.wx.OAuthUtil;
import gt.util.wx.TemplateUtil;
import gt.util.wx.common.WxConstant;
import gt.util.wx.resp.WeixinOauth2Token;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 派费结算微信公众号
 *  用户绑定
 * @author wenyu
 * @date 2017年9月20日 上午9:14:27
 */
@Controller
@RequestMapping("/bound")
public class WxBoundController extends BaseController{

	@Autowired
	private BoundService boundService;
	@Autowired
	private TokenService tokenService;
	/**
	 *  跳转选择快递公司页面
	 * @param HttpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/toBound")
	public String toSettlementBound(HttpServletRequest request){
		//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx26c808cfee0145d1&redirect_uri=http%3A%2F%2Fliuwy.tunnel.qydev.com%2Fgt_cost_settlement%2Fbound%2FtoBound.action&response_type=code&scope=snsapi_base&state=147#wechat_redirect
		String code = request.getParameter("code");
		String state[] = request.getParameter("state").split("_");
		WeixinOauth2Token weixinOauth2Token = null;
		
		 /*weixinOauth2Token = OAuthUtil.getOauth2AccessToken(
					WxConstant.APPID, WxConstant.APPSECRET, code);*/
		if("0".equals(state[1])){
			 weixinOauth2Token = OAuthUtil.getOauth2AccessToken(
					WxConstant.APPID_0, WxConstant.APPSECRET_0, code);
			
		}else{
			 weixinOauth2Token = OAuthUtil.getOauth2AccessToken(
					WxConstant.APPID_1, WxConstant.APPSECRET_1, code);
		}
		 String openId =  null;
		 if (weixinOauth2Token!=null) {
			 openId = weixinOauth2Token.getOpenId();	
			}else{
				//去cookie中拿openId
				 openId = CookieUtil.getWXOpenId(request);
			}
		request.setAttribute("openId", openId);
		request.setAttribute("agentID", state[0]);
		request.setAttribute("wxType", state[1]);
		request.setAttribute("dataSourceType", state[2]);
		return "settle/bind";
	}
	
	/**
	 *  获取可以选择的快递公司
	 * @param agent_id
	 * @return
	 */
	@RequestMapping(value = "/getBoundCarriers", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject getBoundCarriers(String agentId,String dataSourceType){
		
		String urlString = UrlConstant.BOUND_URL + "?agentId="+agentId+"&dataSource="+dataSourceType;
		JSONObject jsonObject =	HttpHelper.sendHttp(urlString);

		 return jsonObject;
	}
	
	/**
	 *  用户绑定操作
	 * @param agent_id
	 * @return
	 */
	@RequestMapping(value = "/doBoundCarriers", method = RequestMethod.POST)
	@ResponseBody
	public String doBoundCarriers(String agentID, String wxType,
			String agentName, String boundCarrierName, String carrierID,
			String carrierSiteID, String carrierSiteName, String openId,
			String dataSourceType) {
		Bound bound = new Bound();
		Bound oldBound = new Bound();
		String result = null;
		if(StringUtils.isNotBlank(agentID)&&StringUtils.isNotBlank(carrierID)&&StringUtils.isNotBlank(openId)){
			
		
			Long carrierId = Long.parseLong(carrierID);
			Long agentId = Long.parseLong(agentID);
			bound.setCarrierId(carrierId);
			bound.setAgentId(agentId);
			
			oldBound.setCarrierId(carrierId);
			oldBound.setAgentId(agentId);
			oldBound.setBoundStatus(1);
			
			bound.setOpenId(openId);
			bound.setBoundStatus(1);
			List<Bound> boundList = new ArrayList<Bound>();
			//if(boundList==null)
			boundList = boundService.queryList(bound);
			
			//再补全bound对象
			bound.setCarrierName(boundCarrierName);
			bound.setCarrierSiteId(Long.parseLong(carrierSiteID));
			bound.setCarrierSiteName(carrierSiteName);
			bound.setAgentName(agentName);
			bound.setBoundStatus(1);
	    	bound.setCreateTime(System.currentTimeMillis());
	    	bound.setUpdateTime(System.currentTimeMillis());
	    	bound.setDataSourceType(Integer.parseInt(dataSourceType));
	    	if(boundList!=null){
				 if(boundList.size()<=0){
					//说明此用户未绑定此站点的此快递公司
					 List<Bound> oldBoundList = boundService.queryList(oldBound);
					if(oldBoundList!=null){
						if(oldBoundList.size()>0){    //此站点已经有人绑定了该快递公司
						//解绑之前的用户
						  
						
							oldBound = oldBoundList.get(0);  //同一站点 同一快递公司，只绑定一个人
							oldBound.setBoundStatus(2);
							boundService.edit(oldBound);
							if("0".equals(wxType)){ 
								String jsonMsg = TemplateUtil.pushTemplateUnboundMessage(oldBound.getOpenId(), WxConstant.UNBOUND_TEMPLATE_ID_0, null, boundCarrierName,agentName);
								//获取token
								Token t = tokenService.queryById(1L);
								//信息推送
								TemplateUtil.sendTemplateMessage(t.getWxKey(), jsonMsg);
							}else if ("1".equals(wxType)){
								String jsonMsg = TemplateUtil.pushTemplateUnboundMessage(oldBound.getOpenId(), WxConstant.UNBOUND_TEMPLATE_ID_1, null, boundCarrierName,agentName);
								//获取token
								Token t = tokenService.queryById(3L);
								//信息推送
								TemplateUtil.sendTemplateMessage(t.getWxKey(), jsonMsg);
							}
							//绑定当前用户
							 boundService.add(bound);
							 result = "1,绑定成功";
					}else{
						//此站点没有人绑定了该快递公司
						Bound userBound = new Bound();
						userBound.setOpenId(openId);
						userBound.setAgentId(agentId);
						userBound.setBoundStatus(1);
						List<Bound> userBoundList = boundService.queryList(userBound);
						if(userBoundList!=null){
						if(userBoundList.size()>0){
							 result = "0,用户已经绑定其他快递公司";
						}else{
							//在根据 openId和CarrierID，status=1查询，判断用户可以绑的快递公司。
							Bound carrierBound = new Bound();
							carrierBound.setOpenId(openId);
							carrierBound.setCarrierId(carrierId);
							carrierBound.setBoundStatus(1);
							List<Bound> uBoundList = boundService.queryList(carrierBound);
							if(uBoundList!=null){
								if(uBoundList.size()>0){
								boundService.add(bound);
									 result = "1,绑定成功";
								}else{
									carrierBound.setCarrierId(null);
								List<Bound> carrierBoundList = boundService.queryList(carrierBound);
								if(carrierBoundList!=null){
									if(carrierBoundList.size()<=0){
											boundService.add(bound);
											 result = "1,绑定成功";
										}else{
											 result = "0,抱歉，您不可以绑定此快递公司";
										}
								}else{
									result = "0,查询失败_4";
								}
							}
						}	
						}
					}else{
						result = "0,查询失败_3";
					}
					}
				 }else{
					 result = "0,查询失败_2";
				 }
				 }else {
					 result = "1,用户已经绑定此快递公司";
				 }
			}else{
				result = "0,查询失败_1";
			}
			}else{
				result = "0,获取参数失败";
			}
		 return result;
	}
	
	/**
	 *  用户绑定操作2
	 * @param agent_id
	 * @return
	 */
	@RequestMapping(value = "/doBoundUser", method = RequestMethod.POST)
	@ResponseBody
	public String doBoundUser(String agentID,String wxType,String agentName,String boundCarrierName,String carrierID,String carrierSiteID,String carrierSiteName,String openId){
		Bound bound = new Bound();
		//解绑功能待修改
		
		String result = null;
		Long carrierId = Long.parseLong(carrierID);
		Long agentId = Long.parseLong(agentID);
		
		
		if(StringUtils.isNotBlank(openId)){
			bound.setOpenId(openId);
			bound.setBoundStatus(1);
			List<Bound> boundList = boundService.queryList(bound);
			//根据openid和status判断
			if(boundList!=null){
				
				bound.setCarrierId(carrierId);
				bound.setAgentId(agentId);
				bound.setCarrierSiteId(Long.parseLong(carrierSiteID));
				bound.setCarrierSiteName(carrierSiteName);
				bound.setAgentName(agentName);
				bound.setBoundStatus(1);
		    	bound.setCreateTime(System.currentTimeMillis());
		    	bound.setUpdateTime(System.currentTimeMillis());
				//如果没查到
				if(boundList.size()<=0){
			    //根据carrierId、agentId和status查询，处理解绑
					//解绑	
					UnBound(carrierId,agentId,bound,wxType);
						
						boundService.add(bound);
				    	result = "1,绑定成功";
					}else{
						result = "0,绑定失败";
					}
				}else{
					//如果查到了，则比较快递公司
					Long oldCarrierId = boundList.get(0).getCarrierId();
					//如果之前绑定的快递公司和当前要绑定的一致，直接绑定
					if(oldCarrierId==carrierId){
						
						boundService.add(bound);
				    	result = "1,绑定成功";
				    //不一致，直接返回
					}else{
						result = "0,用户已经绑定其他快递公司";
					}
					
				}
				
			}else{
				result = "0,绑定失败";
			}
			

		return result;
	}
	
	/**
	 *  解除绑定操作
	 * @param HttpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/UnBound")
	public void UnBound(Long carrierId,Long agentId,Bound bound,String wxType){
		Bound oldBound = new Bound();
		
		oldBound.setCarrierId(carrierId);
		oldBound.setAgentId(agentId);
		oldBound.setBoundStatus(1);
		
		List<Bound> oldBoundList = boundService.queryList(oldBound);
		if(oldBoundList!=null){
			if(oldBoundList.size()>0){
				oldBound = oldBoundList.get(0);  //同一站点 同一快递公司，只绑定一个人
				oldBound.setBoundStatus(2);
				boundService.edit(oldBound);
				if("0".equals(wxType)){ 
					String jsonMsg = TemplateUtil.pushTemplateUnboundMessage(oldBound.getOpenId(), WxConstant.UNBOUND_TEMPLATE_ID_0, null, bound.getCarrierName(),bound.getAgentName());
					//获取token
					Token t = tokenService.queryById(1L);
					//信息推送
					TemplateUtil.sendTemplateMessage(t.getWxKey(), jsonMsg);
				}else if ("1".equals(wxType)){
					String jsonMsg = TemplateUtil.pushTemplateUnboundMessage(oldBound.getOpenId(), WxConstant.UNBOUND_TEMPLATE_ID_1, null,  bound.getCarrierName(),bound.getAgentName());
					//获取token
					Token t = tokenService.queryById(3L);
					//信息推送
					TemplateUtil.sendTemplateMessage(t.getWxKey(), jsonMsg);
				}
				
			}
		}
	}
}
